package la.bbs558.controller.user;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.captcha.LineCaptcha;
import la.bbs558.aop.ratelimit.LimitType;
import la.bbs558.aop.ratelimit.RateLimiter;
import la.bbs558.aop.valid.Check;
import la.bbs558.controller.base.BaseController;
import la.bbs558.controller.base.Result;
import la.bbs558.entity.UserData;
import la.bbs558.service.InvitationCodeService;
import la.bbs558.service.UserDataService;
import la.bbs558.service.VerifyCodeService;
import la.bbs558.util.Objs;
import la.bbs558.util.Strings;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;

/**
 * @Classname VerifyCodeController
 * @Description 验证码
 * @Date 2023/12/15 10:27
 * @Created by weihanmin
 */
@RestController
@RequestMapping("code")
@Check
@RequiredArgsConstructor
@Validated
public class CodeController extends BaseController {
    private final VerifyCodeService verifyCodeService;
    private final InvitationCodeService invitationCodeService;
    private final UserDataService userDataService;

    @GetMapping("createSignInCode")
    @SaIgnore
    @RateLimiter(key = "createSignInCode:",time = 1,count = 5, limitType = LimitType.IP)
    public Result<?> createSignInCode(String username) {
        if(Objs.isInvalid(username)){
            return Result.success();
        }
        LineCaptcha verifyCode = verifyCodeService.createSignInCode(username);
        return Result.success(verifyCode.getImageBase64());
    }

    @GetMapping("sendSignUpCode")
    @SaIgnore
    @RateLimiter(key = "sendSignUpCode:",time = 60,count = 5, limitType = LimitType.IP)
    public Result<?> sendSignUpCode(@NotBlank(message = "邮箱或手机号不能为空") String email) {
        verifyCodeService.sendSignUpCode(email);
        return Result.success();
    }

    @GetMapping("sendForGetCode")
    @SaIgnore
    @RateLimiter(key = "sendForGetCode:",time = 60,count = 1, limitType = LimitType.IP)
    public Result<?> sendForGetCode(@NotBlank(message = "邮箱或手机号不能为空") String email) {
        verifyCodeService.sendForGetCode(email);
        return Result.success();
    }

    @GetMapping("createInviteCode")
    public Result<?> createInviteCode() {
        return Result.success(invitationCodeService.getInviteCode());
    }

    @PostMapping("verifyInviteCode")
    @SaIgnore
    @RateLimiter(key = "verifyInviteCode:",time = 1,count = 1, limitType = LimitType.IP)
    public Result<?> verifyInviteCode(String code) {
        UserData userData = userDataService.verifyInviteCode(code);
        Objs.valid(userData,"邀请码无效");
        Objs.isTrue(Strings.isNotEmpty(userData.getInvitationCode()), "邀请码无效");
        return Result.success();
    }



}
